#include "buttonmanager.h"
#include <QDebug>

ButtonManager* ButtonManager::m_instance = nullptr;
QMutex ButtonManager::mutex;

ButtonManager::ButtonManager()
{
    // 初始化变量
    _rcvByte1 = 0;
    _rcvByte2 = 0;

    for (int i = 1; i <= 10; ++i) {
        buttonStates[i] = false;
    }
}

ButtonManager* ButtonManager::instance()
{
    if (!m_instance) {
        qDebug() << "Trying to create ButtonManager instance...";
        QMutexLocker locker(&mutex);
        if (!m_instance) {
            m_instance = new ButtonManager();
            qDebug() << "ButtonManager instance created.";
        }
    }
    return m_instance;
}

void ButtonManager::handleButtonClick(int buttonId)
{
    if (buttonId >= 1 && buttonId <= 10) {
        QMutexLocker locker(&mutex);
        buttonStates[buttonId] = true;
        emit buttonClicked(buttonId);
        waitCondition.wakeAll();
    }

    //_handleCSDNTestRcv(1, 1);

    qDebug() << " CPP handleButtonClick has click success!!!, receive buttonId :  " << buttonId;
}

QMap<int, bool> ButtonManager::getButtonStates()
{
    QMutexLocker locker(&mutex);
    return buttonStates;
}

void ButtonManager::resetButtonStates()
{
    QMutexLocker locker(&mutex);
    for (int i = 1; i <= 10; ++i) {
        buttonStates[i] = false;
    }
}


void ButtonManager::_handleCSDNTestRcv(int  rcv1, int rcv2)
{
    static int r1 = 1;
    static int r2 = 1;
    //赋值
    _rcvByte1 = r1++;
    _rcvByte2 = r2++;
    //触发信号，QML前端中接收，可搜 activeVehicle.rcvByte1
    emit rcvByte1Changed(_rcvByte1);
    emit rcvByte2Changed(_rcvByte2);

    qDebug() << "[Vehicle] Rcv RcvByte1:" << _rcvByte1;
    qDebug() << "[Vehicle] Rcv RcvByte2:" << _rcvByte2;
}
